package com.eastseeway.radioproject.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.stream.IntStream;

public class ByteUtil {
    public static int isOdd(int num) {
        return num & 0x1;
    }

    public static int HexToInt(String inHex) {
        return Integer.parseInt(inHex, 16);
    }

    public static byte HexToByte(String inHex) {
        return (byte) Integer.parseInt(inHex, 16);
    }

    public static String Byte2Hex(Byte inByte) {
        return String.format("%02x", inByte).toUpperCase();
    }


    public static String ByteArrToHex(byte[] inBytArr) {
        StringBuilder strBuilder = new StringBuilder();
        int j = inBytArr.length;
        for (byte b : inBytArr) {
            strBuilder.append(Byte2Hex(b));
            strBuilder.append(' ');
        }
        return strBuilder.toString();
    }

    public static String ByteArrToHex(byte[] inBytArr, int offset, int byteCount) {
        StringBuilder strBuilder = new StringBuilder();
        for (int i = offset; i < byteCount; i++) {
            strBuilder.append("0x").append(Byte2Hex(inBytArr[i]));
            strBuilder.append(',');
        }
        return strBuilder.toString();
    }

    public static byte[] HexToByteArr(String inHex) {
        int hexlen = inHex.length();
        byte[] result;
        if (isOdd(hexlen) == 1) {
            hexlen++;
            result = new byte[hexlen / 2];
            inHex = "0" + inHex;
        } else {
            result = new byte[hexlen / 2];
        }
        int j = 0;
        for (int i = 0; i < hexlen; i += 2) {
            result[j] = HexToByte(inHex.substring(i, i + 2));
            j++;
        }
        return result;
    }

    /**
     * 截取byte数组   不改变原数组
     * @param b 原数组
     * @param off 偏差值（索引）
     * @param length 长度
     * @return 截取后的数组
     *
     * byte[] a = {(byte)0xAB,0x34,0x56,0x78,(byte)0x91,0x01,0x11,0x21,0x31,0x41,0x51,0x61,0x71,(byte)0x81,(byte)0x92,0x72};
     * Log.e("12121"," "+ByteUtil.ByteArrToHex(ByteUtil.subByte(a,0,4)));
     * 结果是：0xAB,0x34,0x56,0x78,
     */
    public static byte[] subByte(byte[] b,int off,int length){
        byte[] b1 = new byte[length];
        System.arraycopy(b, off, b1, 0, length);
        return b1;
    }

//    字节数组是否全部为0
    public static boolean isEmpty(final byte[] data){
        return IntStream.range(0, data.length).parallel().allMatch(i -> data[i] == 0);
    }

    public static String sha1Str(String input) {
        try {
            if (input == null) {
                return null;
            }

            MessageDigest messageDigest = MessageDigest.getInstance("SHA");
            byte[] digests = messageDigest.digest(input.getBytes());

            StringBuilder output = new StringBuilder();
            for (byte digest : digests) {
                int halfbyte = (digest >>> 4) & 0x0F;
                for (int j = 0; j <= 1; j++) {
                    output.append(
                            ((0 <= halfbyte) && (halfbyte <= 9))
                                    ? (char) ('0' + halfbyte)
                                    : (char) ('a' + (halfbyte - 10)));
                    halfbyte = digest & 0x0F;
                }
            }

            return output.toString();
        } catch (NoSuchAlgorithmException ex) {
            return null;
        }
    }

    public static byte[] convertInteger2Hex(Integer integer){
        String hexString = Integer.toHexString(integer);
        if (hexString.length() > 2) {
            hexString = hexString.substring(hexString.length()-2);
        }
        if (hexString.length() < 2){
            hexString = "0"+hexString;
        }
        int length = hexString.length();
        byte[] b = new byte[length];
        for (int i = 0; i < length; i++) {
            b[i] = (byte) hexString.charAt(i);
        }
        return b;
    }

    /**
     * 将字符串转换成ASCII码
     * @param str 123
     * @return 313233
     */
    public static String convertStringToHex(String str){
        char[] chars = str.toCharArray();
        StringBuffer hex = new StringBuffer();
        for(int i = 0; i < chars.length; i++){
            hex.append(Integer.toHexString(chars[i]));
        }
        return hex.toString();
    }

    /**
     * 将字符串转换成ASCII码字节数组
     * @param str 0123
     * @return 30 31 32 33
     */
    public static byte[] convertStringToHexByte(String str){
        char[] chars = str.toCharArray();
        byte[] hex = new byte[chars.length];
        for(int i = 0; i < chars.length; i++){
            hex[i] = (byte) chars[i];
        }
        return hex;
    }

    /**
     * 将字节数组转换成ASCII码字符串
     * @param bytes 30 31 32 33
     * @return 0123
     */
    public static String convertByteArrayToASCIIString(byte[] bytes){
        StringBuilder sb = new StringBuilder();
        for (byte aByte : bytes) {
            if (aByte == 0) {continue;}
            char c = (char) aByte;
            sb.append(c);
        }
        return sb.toString();
    }

    //49204c6f7665204a617661 split into two characters 49, 20, 4c...
    public static String convertHexToString(String hex){

        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();
        for( int i=0; i<hex.length()-1; i+=2 ){

            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            //convert the decimal to character
            sb.append((char)decimal);

            temp.append(decimal);
        }

        return sb.toString();
    }


    public static byte[] serialize(Object object) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(object);
        oos.flush();
        return bos.toByteArray();
    }

    @SuppressWarnings("unchecked")
    public static <T> T deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bis);
        return (T) ois.readObject();
    }



}